package com.cty.filter;

import com.cty.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @Auther: cty
 * @Date: 2020/2/29 20:55
 * @Description:
 * @version: 1.0
 */
@WebFilter(filterName = "GlobalFilter", urlPatterns = "/*")
public class GlobalFilter implements Filter {
    // 获取日志对象
    Logger log = Logger.getLogger(GlobalFilter.class);

    public void destroy() {
        log.debug("GlobalFilter销毁");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        // 获取SqlSession
        SqlSession session = MyBatisUtil.getSession();
        try {
            // 设置请求编码格式
            req.setCharacterEncoding("utf-8");
            // 设置相应编码格式
            resp.setContentType("text/html;charset=utf-8");
            log.debug("已设置请求和相应的编码格式");

            chain.doFilter(req, resp);  // 放行
            session.commit();  // 提交SqlSession
        } catch (Exception e) {
            session.rollback();  // 回滚
            e.printStackTrace();
        }finally{
            MyBatisUtil.closeSession();  // 关闭SqlSession
        }
    }

    public void init(FilterConfig config) throws ServletException {
        log.debug("GlobalFilter初始化");
    }

}
